package response;

import database.DatabaseHandler;
import database.mysql.ConnectionMySQL;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import json.SimpleJson;


@WebServlet(name = "ResponseServlet", urlPatterns = {"/ResponseServlet"})
public class ResponseServlet extends HttpServlet {

    
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/xml");
        response.setHeader("Cache-Control", "no-cache");
                
        DatabaseHandler dbh = new DatabaseHandler(new ConnectionMySQL("operador", "operador"));       
        
        
        if(request.getParameterMap().containsKey("delete")){
            String object = request.getParameter("delete");
            String id = request.getParameter("id");
            try{
                int modifiedRows = dbh.doChange("DELETE FROM "+object+" WHERE id = "+id);
            }catch(SQLException e){
                String json = "[\"error\",\""+e.getMessage()+"\"]";
                response.getWriter().write(json);
            }
        }
        
        if(request.getParameterMap().containsKey("insert")){
            String object = request.getParameter("insert");
            
            Map params = request.getParameterMap();
            String fieldsValues = dbh.retrieveFieldsValues(params);
           
            try{
                int modifiedRows = dbh.doChange("INSERT INTO "+object+" SET "+fieldsValues);
            }catch(SQLException e){
                String json = "[\"error\",\""+e.getMessage()+"\"]";
                response.getWriter().write(json);
            }
        }
        
        if(request.getParameterMap().containsKey("update")){
            String object = request.getParameter("update");
            String id = request.getParameter("id");
            
            Map params = request.getParameterMap();
            String fieldsValues = dbh.retrieveFieldsValues(params);
            
            try{
                int modifiedRows = dbh.doChange("UPDATE "+object+" SET "+fieldsValues+" WHERE id = "+id);
            }catch(SQLException e){
                String json = "[\"error\",\""+e.getMessage()+"\"]";
                response.getWriter().write(json);
            }
        }
        
        if(request.getParameterMap().containsKey("call")){
            String object = request.getParameter("call");
            
            try{
                ResultSet rs = dbh.getResult("CALL "+object);
                
                response.getWriter().write("[Mensagem: Chamada "+object+" executada]");
            }catch(SQLException e){
                
            }
        }
        
        
        
        if(request.getParameterMap().containsKey("listAll")){
            String object = request.getParameter("listAll");
            String orderBy = "";
            String condition = "";
            SimpleJson sj = new SimpleJson();
            
            if(request.getParameterMap().containsKey("orderBy"))
                orderBy = " ORDER BY "+request.getParameter("orderBy");
            
            //Queba o parametro condition e junta numa string
            if(request.getParameterMap().containsKey("condition")){
                String[] conditionList = request.getParameter("condition").split(",");
                String conditionString = "";
                
                for(int i = 0; i < conditionList.length; i++){
                    String conditionItem = conditionList[i];
                    conditionItem = conditionItem.replace("$$","=");
                    
                    conditionString += conditionItem;
                    if(i > 0) conditionString = " AND " + conditionItem;
                }
                condition = " WHERE " + conditionString;
            }
            
            try{
                ResultSet rs = dbh.getResult("SELECT * FROM "+object+condition+orderBy);
                sj.setResultSet(rs);
                sj.generate();
                response.getWriter().write(sj.getContent());
            }catch(SQLException e){
                
            }
        }
    }
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}